<template>
  <div class="page-main">
    <a-layout style="height: 100%">
      <a-layout>
        <a-layout-content>
          <query-page
            ref="queryPageRef"
            v-model:selectedKeys="selectedKeys"
            :form-component-config="formComponentConfig"
            :form-render-config="formRenderConfig"
            :form-render-keys="renderKeys"
            :table-component-config="tableComponentConfig"
            :table-render-config="tableRenderConfig"
            :table-render-keys="tableRenderKeys"
            :loading="isLoading"
            :data="renderData"
            :total="total"
            title="到货检验类型确认"
            row-selection-type="checkbox"
            @query-data="getData"
            @row-click="handleRowClick"
          >
            <template #top-container>
              <a-tabs v-model="activeKey" @change="changeKey">
                <a-tab-pane key="finishedProduct" title="成品" />
                <a-tab-pane key="rawMaterial" title="原材料" />
                <a-tab-pane key="standardParts" title="标准件" />
                <a-tab-pane key="spareParts" title="零组件" />
                <a-tab-pane key="forgedCastings" title="锻铸件" />
              </a-tabs>
            </template>
            <template #secretLevelName="{ record }">
              <secretLevelInfo
                :record="{
                  secretLevel: record.secretLevel,
                  secretLevelName: record.secretLevelName,
                }"
              />
            </template>
            <template #header-ext-container>
              <a-radio-group
                v-model="position"
                style="margin-top: 16px"
                type="button"
                @change="positionChange"
              >
                <a-radio value="Unspecified">未指定</a-radio>
                <a-radio value="Submission">送检</a-radio>
                <a-radio v-if="activeKey !== 'finishedProduct'" value="Self"
                  >自检</a-radio
                >
              </a-radio-group>
            </template>
            <template #container-side>
              <a-space v-if="position !== 'Unspecified'">
                <a-button
                  v-if="position !== 'Self'"
                  v-permission="['pms:receive-detail-batch-three:updateThrees']"
                  type="primary"
                  :disabled="selectedKeys.length === 0"
                  @click="editPhase"
                  >批量修改三期</a-button
                >
                <a-button
                  v-permission="[
                    `pms:receive-check:${
                      position === 'Self' ? 'selfSubmit' : 'inspectionSubmit'
                    }`,
                  ]"
                  :type="selectedKeys.length === 0 ? 'dashed' : 'outline'"
                  :disabled="selectedKeys.length === 0"
                  @click="handleRefer()"
                  >提交</a-button
                >
              </a-space>
            </template>
            <template #operate="{ record }">
              <a-button
                v-permission="['pms:receive-check:back']"
                :hidden="!['0', '20'].includes(record.status)"
                type="text"
                @click.stop="handleReturn(record)"
                >退回</a-button
              >
              <a-button
                v-permission="['pms:receive-check:updateReceiveCheck']"
                :hidden="
                  !(
                    position !== 'Unspecified' &&
                    ['0', '20'].includes(record.status)
                  )
                "
                type="text"
                @click.stop="handleEdit(record)"
                >编辑</a-button
              >
              <a-button
                v-permission="['pms:receive-check:checkSet']"
                :hidden="
                  !(
                    position !== 'Submission' &&
                    ['0', '20'].includes(record.status)
                  )
                "
                type="text"
                @click.stop="changeStatus(record, '1')"
                >指定为送检</a-button
              >
              <a-button
                v-permission="['pms:receive-check:checkSet']"
                :hidden="
                  !(
                    position !== 'Self' &&
                    activeKey !== 'finishedProduct' &&
                    ['0', '20'].includes(record.status)
                  )
                "
                type="text"
                @click.stop="changeStatus(record, '5')"
                >指定为自检</a-button
              >
            </template>
          </query-page>
        </a-layout-content>
        <a-layout-sider
          v-if="siderFormShow"
          style="width: 400px; padding: 16px"
        >
          <typeSiderForm ref="typeRef" />
        </a-layout-sider>
      </a-layout>
    </a-layout>
    <editPhaseModule
      v-if="editPhaseShow"
      ref="editPhaseRef"
      v-model:edit-phase-show="editPhaseShow"
      @refresh="refresh"
    />
    <div v-permission="['pms:receive-check:updateReceiveCheck']">
      <editModel
        v-if="editModelShow"
        ref="editRef"
        v-model:edit-model-show="editModelShow"
        @refresh="refresh"
      />
    </div>

    <a-modal
      :visible="visible"
      title="退回"
      @cancel="handleCancel"
      @ok="handleOk"
    >
      <a-form ref="formRef" :model="returnObj">
        <a-form-item
          field="rejectReason"
          label="退回原因"
          :rules="[{ required: true, message: '请填写退回原因后在进行退回！' }]"
        >
          <a-input v-model="returnObj.rejectReason" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { nextTick, ref } from 'vue';
  import {
    getReceiveAccept,
    getQueryPage,
    inspectionSubmit,
    selfSubmit,
    updateBack,
    checkSet,
  } from '@/api/admission/typeConfirmation';
  import secretLevelInfo from '@/common/components/secret-level-info/index.vue';
  import { Message } from '@arco-design/web-vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import modalPromise from '@/common/utils/modal-promise';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './form-comp/base-form-config';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './table-comp/base-table-config';

  import editPhaseModule from './component/edit-phase.vue';
  import editModel from './component/edit-model.vue';
  import baseRenderKeys from './table-comp/render-table-columns';
  import typeSiderForm from './component/type-sider-form.vue';

  const tableRenderKeys = ref<any[]>([]);
  const isLoading = ref(true);
  const selectedKeys = ref([]);
  const total = ref(0);
  const renderData = ref<any[]>([]);
  const activeKey = ref('finishedProduct');
  const siderFormShow = ref(false);
  const editPhaseShow = ref(false);
  const editModelShow = ref(false);
  const position = ref('Unspecified');
  // const siderForm = ref({
  //   projectCode: '',
  //   proMdsItemId: '',
  //   calcBasis: '',
  //   validateDate: '',
  //   recheckDate: '',
  //   oilSealDate: '',
  //   mdsInventoryName: '',
  //   refuseManCode: '',
  //   refuseDate: '',
  //   refuseReason: '',
  // });
  const editPhaseRef = ref();
  const editRef = ref();
  const mdsItemType = ref(2);
  const sendType = ref('');
  const visible = ref(false);
  const renderKeys = ref<any>([]);
  const returnObj = ref({});
  const formRef = ref();
  const init = () => {
    const key = `${activeKey.value}${position.value}`;
    tableRenderKeys.value = baseRenderKeys[key];
  };
  init();

  renderKeys.value = [
    'name15',
    'mdsItemId',
    'mdsVendorName',
    'marque',
    'parentItemSerialNo',
    'proMdsItemId',
    'status',
    'receiveType',
  ];
  const handleReturn = (record) => {
    visible.value = true;
    returnObj.value = record;
  };
  const handleCancel = () => {
    visible.value = false;
  };
  const mdsItemTypeList = ref({
    finishedProduct: 2,
    rawMaterial: 3,
    standardParts: 1,
    spareParts: 4,
    forgedCastings: 5,
  });
  const changeKey = (data: any) => {
    mdsItemType.value = mdsItemTypeList.value[data];
    activeKey.value = data;
    siderFormShow.value = false;
    sendType.value = '';
    position.value = 'Unspecified';
    selectedKeys.value = [];
    init();
    getData();
  };
  const getData = async (queryInfo: any = {}) => {
    isLoading.value = true;
    const params = {
      mdsItemType: mdsItemType.value,
      sendType: sendType.value,
      ...queryInfo,
    };
    console.log('params', queryInfo);
    try {
      const { data } = await getQueryPage(params);
      if (data) {
        console.log(data);
        total.value = data.total;
        renderData.value = [...data.list];
      }
      isLoading.value = false;
    } catch (error) {
      Message.warning({
        content: error,
      });
    }
  };
  const refresh = () => {
    getData();
  };
  const typeRef = ref();
  const handleRowClick = async (val) => {
    console.log(val);
    const { data } = await getReceiveAccept(val.id);
    siderFormShow.value = true;
    nextTick(() => {
      typeRef.value.init(data);
    });
  };
  const handleOk = () => {
    formRef.value.validate(async (validate) => {
      if (!validate) {
        if (returnObj.value.status !== '0' && returnObj.value.status !== '20') {
          Message.warning('待送检和检验退回时才可以继续退回！');
          return;
        }
        const { data } = await updateBack(returnObj.value);
        if (data) {
          Message.success('退回成功');
          visible.value = false;
          refresh();
        }
      }
    });
  };
  const changeStatus = async (val, type) => {
    const params = {
      checkIds: [val.id],
      sendType: type,
    };
    const { data } = await checkSet(params);
    if (data) {
      Message.success('操作成功');
      refresh();
    }
  };
  const sendTypeList = ref({
    Submission: '1',
    Self: '5',
    Unspecified: '',
  });
  const positionChange = (data) => {
    sendType.value = sendTypeList.value[data];
    selectedKeys.value = [];
    init();
    getData();
    siderFormShow.value = false;
  };
  const editPhase = () => {
    editPhaseShow.value = true;
    nextTick(() => {
      editPhaseRef.value.ids = selectedKeys.value;
    });
  };
  const handleEdit = (record) => {
    console.log(record);
    editModelShow.value = true;
    nextTick(() => {
      editRef.value.init(record);
    });
  };
  const handleRefer = async () => {
    try {
      await modalPromise.warning({
        title: '请确认',
        content: '您确定要提交选择数据嘛？',
        hideCancel: false,
      });
    } catch {
      return;
    }
    const { data } =
      position.value === 'Submission'
        ? await inspectionSubmit(selectedKeys.value)
        : await selfSubmit(selectedKeys.value);
    if (data) {
      Message.success('提交成功');
      refresh();
    }
    // Modal.warning({
    //   title: '请确认',
    //   content: '您确定要提交选择数据嘛？',
    //   hideCancel: false,
    //   onOk: async () => {
    //     const { data } =
    //       position.value === 'Submission'
    //         ? await inspectionSubmit(selectedKeys.value)
    //         : await selfSubmit(selectedKeys.value);
    //     if (data) {
    //       Message.success('提交成功');
    //       refresh();
    //     }
    //   },
    // });
  };
</script>

<style lang="less" scoped>
  /deep/ .arco-radio-group-button {
    width: 100%;
  }

  /deep/ .arco-radio-button {
    width: 50%;
    color: #4e5769 !important;
    text-align: center;
  }

  /deep/ .arco-radio-button.arco-radio-checked {
    color: #1e2228 !important;
  }
</style>
